package com.liang.jiekou.service.impl;

import com.liang.jiekou.service.HttpClientService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class HttpClientServiceImpl implements HttpClientService {
    // 注入HttpClient
    @Resource
    private CloseableHttpClient httpClient;

    // 注入Jackson的ObjectMapper，用于将Map转换为JSON字符串
    @Resource
    private ObjectMapper objectMapper;


    @Override
    public String postRequest(String url, String aramsJson) throws IOException {
        // 创建HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 将参数转换为json字符串并设置到httpPost实体中
        //String jsonParams = objectMapper.writeValueAsString(params);
        httpPost.setEntity(new StringEntity(aramsJson, "UTF-8"));

        // 发送请求并获取响应
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 获取响应体
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

        return responseBody;

    }
}
